<template>
  <div class="detail-container" v-loading="loading">
    <el-card shadow="never" style="margin-top: 15px">
      <div class="operate-container">
        <i class="el-icon-warning color-danger" style="margin-left: 20px"></i>
        <span class="color-danger">当前合同状态：{{orderInfo.applyState | fifpayState}}</span>
        <div style="float:right;margin-top:20px;margin-right:20px;line-height: 20px;">
          <el-button type="primary"  size="small" @click="showPrint">打印</el-button>
          <div style="text-align: center;font-size: 12px">已打印 {{orderInfo.hasPrintNum}} 次</div>
        </div>

      </div>
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">基本信息</span>
      </div>
      <el-card shadow="never" style="margin-top:20px">
        <el-form  size="mini" label-width="150px" class="minRoW">
          <el-row>
            <el-col :span="8">
              <el-form-item label="结算单号：">{{orderInfo.applySn}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收款方：">{{orderInfo.agentProcessor}}</el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="付款方：" >{{orderInfo.fromCompany}}</el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="付款方式：">{{orderInfo.applyPaymentCode | fifPaymentCode}}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申请付款金额：">{{ orderInfo.applyPayAmount }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际支付费用：">{{ orderInfo.payAmount }}</el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="申请时间：">{{ orderInfo.applyTime }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申请人：">{{ orderInfo.applyUserName }}</el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同附件：">
                  <img :src="item" v-for="item in orderInfo.applyPayContract" style="width:50px;height:50px;object-fit: contain" @click="fullImg(item)"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="付款时间：">
                {{ orderInfo.payTime }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="付款人：">
                {{ orderInfo.payUserName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="付款凭证：">
                 <img :src="orderInfo.payContent" style="width:50px;height:50px;object-fit: contain"  v-if="orderInfo.payContent != ''" @click="fullImg(orderInfo.payContent)"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="申请备注：">
                  {{orderInfo.applyPayRemark}}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="付款备注：">
                {{orderInfo.payRemark}}
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </el-card>

      <div style="margin-top: 20px;clear: both">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">入库加工单</span>
      </div>

      <el-table
        ref="orderItemTable"
        :data="orderInfo.goodsList"
        style="width: 100%;margin-top: 20px" border>
        <el-table-column label="单据编号"  width="100" align="center">
          <template slot-scope="scope">
              {{scope.row.entrySn}}
          </template>
        </el-table-column>
        <el-table-column label="加工商" width="160" align="center">
          <template slot-scope="scope">
            {{scope.row.agentProcessor}}
          </template>
        </el-table-column>
        <el-table-column label="商品名称"   width="150"  align="center">
          <template slot-scope="scope">
            {{scope.row.goodsName}}
          </template>
        </el-table-column>
        <el-table-column label="数量"   width="100" align="center">
          <template slot-scope="scope">
            {{scope.row.goodsNum}}
          </template>
        </el-table-column>
        <el-table-column label="单位" width="100" align="center">
          <template slot-scope="scope">
            {{scope.row.goodsUnit}}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150" align="center">
          <template slot-scope="scope">
            {{scope.row.goodsRemark}}
          </template>
        </el-table-column>
        <el-table-column label="原料采购订单号" width="150" align="center">
          <template slot-scope="scope">
            {{scope.row.materialOrderSn}}
          </template>
        </el-table-column>
        <el-table-column label="原料单价" width="100" align="center">
          <template slot-scope="scope">
            {{scope.row.materialPrice}}
          </template>
        </el-table-column>
        <el-table-column label="加工费" width="100" align="center">
          <template slot-scope="scope">
            {{scope.row.processingFee}}
          </template>
        </el-table-column>
        <el-table-column label="加工费总额" width="100" align="center">
          <template slot-scope="scope">
            {{scope.row.processingFeeAmount}}
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:20px;font-size:12px;color:#606266" v-if="orderInfo.goodsList">单据数量：{{ orderInfo.goodsList.length }}条<span style="padding-left:10px;">申请付款金额：{{ orderInfo.applyPayAmount }}</span></div>
      <div style="margin-top:20px">
        <el-form ref="orderInfo" size="small" inline>
          <el-form-item label="备注（回退/取消时必填）："  >
            <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" style="width:300px" v-model.trim="remark"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align: center;clear: both;margin-top:20px">
            <el-button type="primary" @click="showDialog"  v-if="orderInfo.isCanPay == 1">付 款</el-button>
            <el-button type="primary" @click="handleConfirm('pass')" v-if="orderInfo.isNeedMyCheck == 1" :loading="btnLoading">审 核</el-button>
            <el-button @click="handleConfirm('back')" :loading="btnLoading1" v-if="orderInfo.isNeedMyCheck == 1">回 退</el-button>
            <el-button @click="handleConfirm('cancel')" :loading="btnLoading2" v-if="orderInfo.isCanCancel == 1">取 消</el-button>
      </div>

      <div style="margin-top: 20px;clear: both">
        <el-menu :default-active="logTab" class="el-menu-demo" mode="horizontal" >
          <el-menu-item index="1">操作记录</el-menu-item>
        </el-menu>
      </div>

      <div style="margin-top:20px;border:1px solid #EBEEF5;padding:20px 20px 0 20px">
        <div v-if="logTab == 1 || logTab == 2 || logTab == 3">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in orderInfo.logList"
              :key="index">
                         <span>
                             <span style="padding-right:10px;">{{activity.logTime}}</span>
                             {{activity.logUserName}}：{{activity.logContent}}
                             <span v-show="activity.logRemark && activity.logRemark != ''" style="color:red;padding-left:5px">备注：{{activity.logRemark}}</span>
                         </span>
            </el-timeline-item>
          </el-timeline>
          <div style="color:#888;padding:20px;text-align: center;font-size:12px" v-if="orderInfo.logList && orderInfo.logList.length == 0">- 暂无数据 -</div>
        </div>
      </div>
    </el-card>


    <!--放大图片-->
    <el-dialog
      :visible.sync="dialogVisible4"
      width="800px">
      <img :src="fullSrc" style="width:100%;"/>
    </el-dialog>

    <!--付款-->
    <el-dialog
      :close-on-click-modal="false"
      title="付款"
      :visible.sync="dialogVisible"
      width="600px">
      <el-form :model="payForm" size="mini" label-width="100px" ref="payForm" :rules="rules">
        <el-form-item label="收款方：" >
            {{ orderInfo.agentProcessor }}
        </el-form-item>
        <el-form-item label="收款金额：">
          {{ orderInfo.applyPayAmount }}
        </el-form-item>
        <el-form-item label="付款日期：" >
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="payForm.payTime"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="付款凭证：" prop="payContent">
          <div style="width: 100%;height: 150px; border:1px solid #DCDFE6;cursor: default;border-radius: 4px;">
            <img id="imgNode" :src="payForm.payContent" style="width:100%;height:100%;object-fit: contain;border:0" v-show="payForm.payContent != ''">
            <el-input type="hidden" v-model="payForm.payContent"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="付款备注：" >
          <el-input type="textarea" :rows="2" v-model="payForm.payRemark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm4" :loading="btnLoading4">确 定</el-button>
      </span>
    </el-dialog>

    <!--打印弹窗-->
    <el-dialog
      :close-on-click-modal="false"
      :beforeClose="closePrint"
      :visible.sync="dialogVisible6"
      width="900px">
      <div id="print-div" style="height:100%;background: #fff">
        <div class="paper-top">
          <table border="0" cellpadding="0" cellspacing="0" style="width:100%" class="pring-table">
            <tr>
              <td style=" white-space:nowrap;" valign="top" width="25%">付款编号：</td>
              <td valign="top" width="25%">{{orderInfo.applySn}}</td>
              <td style=" white-space:nowrap;" valign="top" width="25%">付款时间：</td>
              <td valign="top" width="25%">{{orderInfo.payTime}}</td>
            </tr>
            <tr>
              <td style=" white-space:nowrap;" valign="top" width="25%">收款方：</td>
              <td valign="top" width="25%">{{orderInfo.agentProcessor}}</td>
              <td style=" white-space:nowrap;" valign="top" width="25%">付款金额:</td>
              <td  valign="top" width="25%">{{orderInfo.applyPayAmount }}</td>
            </tr>
            <tr>
              <td style=" white-space:nowrap;" valign="top" width="25%">申请备注：</td>
              <td valign="top" width="25%">{{orderInfo.applyPayRemark}}</td>
              <td style=" white-space:nowrap;" valign="top" width="25%">申请人：</td>
              <td valign="top" width="25%">{{orderInfo.applyUserName}}</td>
            </tr>
          </table>
        </div>
        <div style="margin-top: 20px;clear: both">
          <el-menu :default-active="logTab" class="el-menu-demo" mode="horizontal">
            <el-menu-item index="1">操作记录</el-menu-item>
          </el-menu>
        </div>
        <div style="margin-top:20px">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in orderInfo.logList"
              :key="index">
                   <span>
                       <span style="padding-right:10px;">{{activity.logTime}}</span>：{{activity.logUserName}} {{activity.logContent}}
                       <span v-show="activity.logRemark && activity.logRemark != ''" style="color:red;padding-left:5px">备注：{{activity.logRemark}}</span>
                   </span>
            </el-timeline-item>
          </el-timeline>
          <div style="color:#888;padding:20px;text-align: center;font-size:12px" v-if="orderInfo.operateLogs && orderInfo.operateLogs.length == 0">- 暂无数据 -</div>
        </div>

      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" size="small" style="width:150px;" @click="printdiv">打印</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
const defaultPayForm={
  "applyId" : '',  //付款申请单ID
  "payContent" : "", //付款凭证
  "payRemark" : "", //付款备注
  "payTime" : "" //支付日期
};
import { mapGetters } from 'vuex'
import axios from 'axios'
import store from '@/store'
import { getQiniuToken,uploadBase64,agentProcessApplyInfo,agentProcessApplyProcess,agentProcessApplyPay,agentProcessUpdatePrintNum,syncOneKingOrderPurchase,getOrderUsersList,changeBuyerUserId} from '@/api/partner'
import {validateCommission} from '@/utils/validate';
import "@/utils/jQuery.print"
export default {
  name: "customerDetail",
  data(){
    return{
      loading:false,
      orderInfo:{},
      logTab:'1',
      userOptionList:[],
      remark:'',
      dialogVisible4:false,
      fullSrc:'',
      btnLoading:false,
      btnLoading1:false,
      btnLoading2:false,
      payForm:JSON.parse(JSON.stringify(defaultPayForm)),
      rules:{
        payContent:[{required: true, trigger: 'change',message: '此项必填',}],
      },
      dialogVisible:false,
      upUrl:'',
      uploadToken:{
        token:'',
      },
      imgDomain:'',
      btnLoading4:false,
      dialogVisible6:false,
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId',
      'isMange',
    ]),
  },
  watch:{
    upUrl(){
      let data = {};
      let pic = this.upUrl.replace(/^.*?base64,/, '');
      data.pic = pic;
      data.token = this.uploadToken.token;
      data.imgDomain = this.imgDomain;
      uploadBase64(data).then((res)=>{
        if(res.src){
          this.payForm.payContent = res.src;
        }else{
          this.$message.error('上传失败')
        }
      });
    },
  },
  created() {
    this.getPageInfo();
    this.pasteImage();
  },


  filters: {
    fifpayState(val){
      if(val == 0){
        return '待采购员审核'
      }else if(val == 10){
        return '作废'
      }else if(val == 20){
        return '待采购部门负责人确认'
      }else if(val == 30){
        return '待财务负责人审核'
      }else if(val == 40){
        return '待支付'
      }else if(val == 50){
        return '已支付'
      }
    },
    fifPaymentCode(val){
      if(val == 'cash'){
        return '现金汇款'
      }else if(val == 'chengdui'){
        return '承兑'
      }
    },
  },

  methods:{
    //显示打印弹窗
    showPrint(){
      this.dialogVisible6 = true;
    },
    //关闭打印弹窗
    closePrint(){
      this.dialogVisible6 = false;
      this.getPageInfo()
    },

    //打印
    printdiv(){
      agentProcessUpdatePrintNum({applyId:this.$route.query.id});
      $("#print-div").print({
        globalStyles:true,//是否包含父文档的样式，默认为true
        mediaPrint:true,//是否包含media='print'的链接标签。会被globalStyles选项覆盖，默认为false
        stylesheet:null,//外部样式表的URL地址，默认为null
        noPrintSelector:".no-print",//不想打印的元素的jQuery选择器，默认为".no-print"
        iframe:true,//是否使用一个iframe来替代打印表单的弹出窗口，true为在本页面进行打印，false就是说新开一个页面打印，默认为true
        append:null,//将内容添加到打印内容的后面
        prepend:null,//将内容添加到打印内容的前面，可以用来作为要打印内容
        deferred: $.Deferred()//回调函数
      });
    },

    handleConfirm4(){
      this.$refs.payForm.validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.payForm))
          data.applyId = this.$route.query.id;
          this.btnLoading4 = true;
          agentProcessApplyPay(data).then(()=>{
            this.btnLoading4 = false;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.dialogVisible = false;
            this.getPageInfo()
          }).catch(()=>{
            this.getPageInfo()
          })

        }
      })
    },

    //显示付款弹窗
    showDialog(){
      this.dialogVisible = true;
      this.getUploadToken();

    },

    //获取七牛TOKEN
    getUploadToken(){
      return getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },

    //粘贴图片
    pasteImage() {
      let upUrl = ''
      document.addEventListener('paste',(event)=> {
        let isChrome = false;
        if (event.clipboardData || event.originalEvent) {
          //某些chrome版本使用的是event.originalEvent
          let clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
          if(clipboardData.items){
            // for chrome
            let  items = clipboardData.items, len = items.length, blob = null;
            isChrome = true;
            for (let i = 0; i < len; i++) {
              if (items[i].type.indexOf("image") !== -1) {
                //getAsFile() 此方法只是living standard firefox ie11 并不支持
                blob = items[i].getAsFile();
              }
            }
            if(blob!==null){
              let blobUrl=URL.createObjectURL(blob);
              // this.priceForm.blobImg = blobUrl;
              // document.getElementById("imgNode").src=blobUrl;
              let reader = new FileReader();
              // base64码显示
              reader.onload =  (event)=> {
                // event.target.result 即为图片的Base64编码字符串
                // this.priceForm.payContent = event.target.result;
                // document.getElementById("imgNode").src=base64_str;
                this.upUrl = event.target.result;
              };
              reader.readAsDataURL(blob);
            }
          }
        }
      });
    },

    handleClose(){
      this.dialogVisible = false;
    },

    fullImg(src){
      this.dialogVisible4 = true;
      this.fullSrc = src;
    },


    //返回
    goBlack(){
      this.$router.go(-1)
    },

    //确认提交
    handleConfirm(action){
          let data = {};
          data.applyId = this.$route.query.id;
          if( action == 'pass'){
           if(this.orderInfo.applyState == 0){
              data.action = 'applyCheck'
            }else if(this.orderInfo.applyState == 20){
              data.action = 'purchaseCheck'
            }else if(this.orderInfo.applyState == 30){
              data.action = 'financeCheck'
            }
          }else{
            data.action = action;
          }
          if((data.action == 'back' || data.action == 'cancel') && this.remark == ''){
            this.$message({
              message: '请填写备注',
              type: 'error',
              duration: 1000
            });
            return false
          }

          if(action == 'pass'){
            this.btnLoading = true;
          }else if(data.action == 'back'){
            this.btnLoading1 = true;
          }else if(data.action == 'cancel'){
            this.btnLoading2 = true;
          }
          agentProcessApplyProcess(data).then(()=>{
            this.btnLoading = false;
            this.btnLoading1 = false;
            this.btnLoading2 = false;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.getPageInfo();
          }).catch(()=>{
            this.btnLoading = false;
            this.btnLoading1 = false;
            this.btnLoading2 = false;
          })


    },


    //获取合同详情
    getPageInfo(){
      this.loading = true;
      agentProcessApplyInfo({applyId:this.$route.query.id}).then(res=>{
        this.orderInfo = res;
        this.loading = false;
      });
    },
  },

}
</script>

<style  lang="scss" scoped>
.avatar-uploader{
  margin-bottom:10px;
  display: inline-block;
  width:80px;
  height:80px;
  border:1px solid #DCDFE6;
  text-align: center;
  line-height: 80px;
}
.detail-form{
  .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
    margin-bottom:0px;
  }
}

.detail-container {
  width: 90%;
  padding: 20px 20px 20px 20px;
  margin: 20px auto;
  .el-card__header{
    background: #f8f8f8;
    .kehu-name{
      display: inline-block;
      font-size:14px;
      vertical-align: middle;
    }
    .kehu-label{
      font-size:12px;
      vertical-align: middle;
      display: inline-block;
      margin-left:15px;
      color: #409eff;
      background: #ecf5ff;
      border: 1px solid #b3d8ff;
      height:24px;
      line-height: 24px;
      padding:0 10px;
      border-radius: 5px;
    }
    .kehu-info{
      text-align: right;
      font-size: 12px;
      color:#333;
      line-height: 20px;
      span{
        padding-left:16px;
      }
    }
  }
  .operate-container {
    background: #F2F6FC;
    height: 80px;
    margin: -20px -20px 0;
    line-height: 80px;
  }
}
.price-block{
  font-size:12px;
  line-height:30px;
  .lab{
    display: inline-block;
    width:100px;
    text-align: right;
  }
  .text{
    display: inline-block;
  }
}
#print-div{
  font-size:12px;
  font-family: "Microsoft YaHei";
  color:#000;
  .title{
    font-size:24px;
    font-weight: bold;
    text-align: center;
    line-height: 40px;
  }
  .paper-top{
    margin-top:20px;
    line-height: 30px;
  }
  .good-table{
    margin-top:20px;
    table{
      border-left:1px solid #000;
      border-bottom:1px solid #000;
      td,th{
        font-weight: normal;
        border-right:1px solid #000;
        border-top:1px solid #000;
        padding:5px 10px;
        line-height: 20px;
      }
    }
  }
  .paper-bottom{
    margin-top:10px;
    line-height: 20px;
  }
  .pring-table{
    border-top:1px solid #000;
    border-right:1px solid #000;
    td{
      border-bottom:1px solid #000;
      border-left:1px solid #000;
      padding:0 10px;
    }
  }
}
</style>
